package com.guardchina.framework.util.utils;

import com.guardchina.framework.util.exception.BusinessException;
import org.apache.commons.lang3.StringUtils;

import java.util.Random;

/**
 * 描述：随机数工具类
 *
 * @author lwb
 * @date 2019/5/7 10:50
 */
public class RandomUtil {

    /**
     * 生成随机数字
     * @param length 数字位数
     * @return 随机 {size} 位数字
     */
    public static String randomNumber(int length){
        String characters = "0123456789";
        return randomString(characters, length);
    }

    /**
     * 获取随机数字
     * @param min 最小值
     * @param max 最大值
     * @return 随机数字
     */
    public static Integer randomNumber(Integer min, Integer max){

        if(max < min){
            throw new BusinessException("最大值小于最小值");
        }

        if(max.intValue() == min.intValue()){
            return min;
        }

        Integer section = max - min;

        Random random = new Random();

        return  random.nextInt(section) + min;

    }

    /**
     * 生成随机字符串
     * @param length 随机字符串长度
     * @return 随机字符串
     */
    public static String randomString(int length){
        String characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        return randomString(characters, length);
    }

    /**
     * 从指定字符中获取随机字符串
     * @param characters 指定字符串
     * @param length 随机字符串长度
     * @return 随机字符串
     */
    public static String randomString(String characters, int length){
        if(StringUtils.isEmpty(characters)){
            return "";
        }
        if(length <= 0){
            return "";
        }
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for(int i=0; i<length; i++){
            int index = random.nextInt(characters.length());
            sb.append(characters.charAt(index));
        }
        return sb.toString();
    }
}
